import requests
# from threading import Thread
import time
import base64
import json
import getsq, swpng
from myconfig import *
import os
import re
from decodedat import do


class wechat:

    def __init__(self, wxpath='F:\weixinfiles\WeChat Files') -> None:
        self.url = "http://127.0.0.1:8080/api"
        self.wxid = None
        self.wxpath = wxpath
        # self.server_url = "https://api.u96242.nyat.app:39311"
        self.server_url = "http://127.0.0.1:5000"

    def sendTextMsg(self, target_wxid: str, text: str):
        data = {"wxid": target_wxid, "content": text}
        resp = requests.post(url=self.url + "/sendtxtmsg", json=data)
        if resp.json()["code"] == 200:
            with open("sendlog.txt", "a", encoding="utf8") as f:
                f.write(f"{int(time.time())}:{target_wxid}&{text}\n")
            return True
        else:
            return False

    def sendImageMsg(self, target_wxid: str, image64: bytes):
        data = {
            "wxid": target_wxid,
            "image": base64.b64encode(image64).decode()
        }
        resp = requests.post(url=self.url + "/sendimgmsg", json=data)
        # print(resp.json())
        if resp.json()["code"] == 200:
            return True
        else:
            return False

    def sendFileMsg(self, target_wxid: str, file_data: bytes):
        data = {"wxid": target_wxid}
        files = {
            'file': file_data,
            'clear': "false",
        }
        resp = requests.post(url=self.url + "/sendfilemsg",
                             data=data,
                             files=files)
        # print(resp.json())
        if resp.json()["code"] == 200:
            return True
        else:
            return False

    def check_login(self):
        resp = requests.get(url=self.url + "/checklogin")
        resp_json = resp.json()
        if resp_json["code"] == 200:
            self.wxid = resp_json["data"]['wxid']
        return resp.json()

    def get_dbcontacts(self):
        resp = requests.get(url=self.url + "/dbcontacts")
        resp_json = resp.json()
        if resp_json["code"] == 200:
            # print(resp.json())
            with open('contacts.json', 'w', encoding='utf8') as f:
                json.dump(resp_json['data'], f, ensure_ascii=False)

    def get_dbchatroom(self, chatroom):
        resp = requests.get(url=self.url + f"/dbchatroom?wxid={chatroom}")
        resp_json = resp.json()
        if resp_json["code"] == 200:
            # print(resp.json())
            with open(f'{chatroom}.json', 'w', encoding='utf8') as f:
                json.dump(resp_json['data'], f, ensure_ascii=False)

    def get_dbaccountbywxid(self, wxid):
        resp = requests.get(url=self.url + f"/dbaccountbywxid?wxid={wxid}")
        resp_json = resp.json()
        # print(resp_json)
        if resp_json["code"] == 200:
            # print(resp.json())
            try:
                result = resp_json['data']['NickName']
            except Exception as e:
                print(e)
                result = None
            return result

    def forward_msg(self, wxid, msgid):
        """
        转发消息
        wxid string：本次转发消息的接收对象
        
        msgId uint64|string：消息id（通常可以用消息回调或者websocket回调获取到，当前是消息回调中的MsgSvrID字段）
        """
        resp = requests.get(url=self.url +
                            f"/forwardmsg?wxid={wxid}&msgId={msgid}")
        resp_json = resp.json()
        return resp_json

    def get_sw(self, strTalker):
        # self.sendTextMsg(strTalker, "开始查询")
        try:
            swpng.getswpng(ID_list=swid_list, imgtype=1)
            for _id in swid_list:
                with open(
                        f"{os.path.dirname(__file__)}{os.sep}data{os.sep}{_id[0]}_{1}.png",
                        "rb") as img:
                    self.sendImageMsg(strTalker, img.read())
        except Exception as e:
            print(e)
        # try:
        #     sq = getsq.getnewsq("刘涧")
        # except Exception as e:
        #     sq = str(e)
        #     print(e)
        # self.sendTextMsg(strTalker, sq)
    def get_kg(self, strTalker):
        '''
        获取开高
        '''

    def get_qs(self, strTalker):
        img_data = swpng.getswpng(ID_list=swid_list, imgtype=2)
        self.sendImageMsg(strTalker, img_data)
        img_data = swpng.getqspng("刘涧")
        self.sendImageMsg(strTalker, img_data)

    def get_1zhan(self, strTalker):
        gq = getsq.getnewgq("0")
        self.sendTextMsg(strTalker, gq)

    def get_2zhan(self, strTalker):
        gq = getsq.getnewgq("1")
        self.sendTextMsg(strTalker, gq)

    # 获取能源单耗水位
    def get_nysw(self, strTalker):
        sw = getsq.getnysw(0)
        self.sendTextMsg(strTalker, sw)

    def forward_img(self, wxid, target_wxid, BytesExtra):
        temp = (base64.b64decode(BytesExtra))
        t = re.findall(rb'(FileStorage.*?.dat)', temp)
        if t:
            dat_path = f"{self.wxpath}{os.sep}{wxid}{os.sep}{t[0].decode('utf8')}"
            print(dat_path)
            img_path = do(dat_path)
            print(img_path)
            try:
                with open(img_path, 'rb') as f:
                    self.sendImageMsg(target_wxid, f.read())
            except Exception as e:
                print('图片转发失败：', e)
            # self.sendImageMsg(target_wxid, img64)

    def send_server(self, nick, msg):
        '''
        信息保存到服务器数据库
        '''
        while 1:
            try:
                resp = requests.get(
                    url=f'{self.server_url}/diancan?n={nick}&t=0&d={msg}',
                    verify=False)
                if resp.status_code == 200:
                    print('发送成功')
                    return True
                else:
                    print('发送失败')
                    return False
            except Exception as e:
                print(f"An error occurred: {e}")
                time.sleep(1)

    def sendSQToServer(self, text):
        '''
        把水情发到服务器里
        '''
        resp = requests.get(
            f'{self.server_url}/sqnotice',
            params={'text': text},
        )
        if resp.status_code == 200:
            print('发送成功')
            return True
        else:
            print('发送失败')
            return False

    # // 解密base64数据messageRaw.BytesExtra
    # const base64Data = messageRaw.BytesExtra // 这是你的Base64数据
    # const decodedData = Buffer.from(base64Data, 'base64').toString('utf8')
    # // console.log('解密后的数据：', decodedData)
    # const regex = /FileStorage(.*?)\.dat/g
    # const results = []
    # let result
    # while ((result = regex.exec(decodedData)) !== null) {
    #   // console.log('Found:', result)
    #   const path = `${this.currentUserId}\\${result[0]}`
    #   // console.log('path:', path)
    #   results.push(path)
    # }

    # console.log('results:', result)


if __name__ == "__main__":
    w = wechat()
    # w.get_dbcontacts()
    print(w.get_dbaccountbywxid("39313362304@chatroom"))
    # print(w.forward_msg("filehelper", "7362186284857269667"))
    # if w.check_login():
    #     print(w.wxid)
    #     w.sendTextMsg("filehelper", "hello")
    #     with open("add.png",'rb')as f:
    #         w.sendFileMsg("filehelper", f.r())
#
